﻿#region using
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using Jsil.Compiler;
using Jsil.Runtime;
#endregion using

namespace Sample
{
	class Program
	{
		static void Main(string[] args)
		{
			string projectBasePath=Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory))));
			Directory.CreateDirectory(projectBasePath+@"\dll");

			foreach (string filePath in Directory.GetFiles(projectBasePath+@"\dll"))
				File.Delete(filePath);

			string script;
			//script=@"import lib1=\RuntimeCopyDebugHelper\bin\debug\RuntimeCopyDebugHelper.dll; var a=0; var b=1; var c=a!=b; c=lib1; c=c.RuntimeCopyDebugHelper.Class.Const; Output(c);";
			//script="var a=666; function f1(b){a=b;} function f2(a){a=b;} f1(a); var z=new function(){this.x=3;this.y=5;function XXX(a,b){return a+b};this.zzz=XXX(a+9,this.y);}; Output(z);";
			//script="var g=8; function f1(){var a=0; g+=3;} function f2(){var b=0; g+=2; f1(); if (g<=20) f2();} debugger; f2(); Output(g);";
			//script="var c=3; var d=5; Output(c+d);";
			//script="var a={x:0,y:0}; Output(a);";
			//script="Output(new Date());";
			//script="try{ throw new Error(200,'x equals zero'); } catch(ex){ Output(ex.message); }";
			script=File.ReadAllText(projectBasePath+@"\sample\samplescript.js");

			string pathDll=projectBasePath+@"\dll\mpjs.dll";
			MpJScriptCompiler.Compile(script,pathDll,new CompilerOptions() { Debug=true,RuntimeMethodsUsage=RuntimeMethodsUsage.Call });

			Executor asmExec=new Executor(Assembly.LoadFrom(pathDll));
			asmExec.ExternalVariables["Output"]=new Func<object,object>(delegate(object text) { Console.Write(text); return null; });
			asmExec.ExternalVariables["DataLoader"]=MpJsDataLoader.Singleton;
			asmExec.ResolveExternalLibrary+=asmExec_ResolveExternalLibrary;
			asmExec.Execute();

			Console.ReadKey();
		}

		static void asmExec_ResolveExternalLibrary(object sender,Jsil.Runtime.ResolveExternalLibraryEventArgs e)
		{
			string projectBasePath=Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory)));
			e.Assembly=projectBasePath+e.Predefinition;
		}
	}
}
